package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.mapper.*;
import com.tanhua.common.pojo.*;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.SoundApi;
import com.tanhua.oss.OssTemplate;
import com.tanhua.server.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TestSoulService {
    @Autowired
    private QuestionnaireResultMapper questionnaireResultMapper;

    @Autowired
    private QuestionUserLockMapper questionUserLockMapper;

    @Autowired
    private QuestionnaireMapper questionnaireMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private QuestionnaireReportMapper questionnaireReportMapper;

    @Autowired
    private SoulQuestionOptionMapper soulQuestionOptionMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Reference
    private SoundApi soundApi;
    @Autowired
    private SoulQuestionMapper soulQuestionMapper;
    @Autowired
    private OssTemplate ossTemplate;

    /**
     * 问卷列表
     * @return
     */
    public List<QuestionnaireVo> SQuestionnaireLike() {
        //拿到用户id
        User user = UserThreadLocal.get();
        //要返回的vo对象
        List<QuestionnaireVo> questionnaireVoList = new ArrayList<>();

        //通过user_Id找到QuestionUserLock表中的user_id拿到问卷id和锁状态存到问卷vo里面
        QueryWrapper<QuestionUserLock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());
        List<QuestionUserLock> questionUserLock3 = this.questionUserLockMapper.selectList(queryWrapper);
        //查询的questionUserLock是空表示用户没有做过题目,在lock表中添加数据
        if (ObjectUtil.isEmpty(questionUserLock3)){
            QuestionUserLock questionUserLock1 = new QuestionUserLock();
            questionUserLock1.setUserId(user.getId());
            questionUserLock1.setQuestionnaireId(1L);
            questionUserLock1.setIsLock(0);
            questionUserLockMapper.insert(questionUserLock1);
            questionUserLock1.setQuestionnaireId(2L);
            questionUserLock1.setIsLock(1);
            questionUserLockMapper.insert(questionUserLock1);
            questionUserLock1.setQuestionnaireId(3L);
            questionUserLock1.setIsLock(1);
            questionUserLockMapper.insert(questionUserLock1);
        }

        List<QuestionUserLock> questionUserLock = this.questionUserLockMapper.selectList(queryWrapper);
        for (QuestionUserLock questionUserLocks : questionUserLock) {
            QuestionnaireVo questionnaireVo = new QuestionnaireVo();
            questionnaireVo.setId(questionUserLocks.getQuestionnaireId()+"");
            questionnaireVo.setIsLock(questionUserLocks.getIsLock());
            questionnaireVoList.add(questionnaireVo);
        }

        //拿出问卷Id的集合 1,2,3
        List<Object> questionnaireId = CollUtil.getFieldValues(questionUserLock, "questionnaireId");

        //通过拿到的问卷id找到问题表中的数据存在返回问卷vo中
        LambdaQueryWrapper<Questionnaire> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.in(Questionnaire::getId, questionnaireId);
        List<Questionnaire> soulQuestionnaire = this.questionnaireMapper.selectList(queryWrapper2);
        for (Questionnaire questionnaire : soulQuestionnaire) {
            for (QuestionnaireVo questionnaireVo : questionnaireVoList) {
                //把返回vo中的id与从问题表中拿到的id进行对比,确定存放的是同一个vo返回对象
                if (questionnaire.getId().toString().equals(questionnaireVo.getId().toString())) {
                    questionnaireVo.setLevel(questionnaire.getLevel()+"");
                    questionnaireVo.setName(questionnaire.getName());
                    questionnaireVo.setCover(questionnaire.getCover());
                    questionnaireVo.setStar(questionnaire.getStar());
                }
            }
        }

        //把问题vo填充到问卷vo中
        for (QuestionnaireVo questionnaireVo : questionnaireVoList) {
            //拿到试题数据
            QueryWrapper<SoulQuestion> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.eq("questionnaire_id", questionnaireVo.getId());
            //List<SoulQuestionVo> questions;字段中还缺少SoulQuestionVo集合
            //从数据库中拿到SoulQuestionVo信息
            List<SoulQuestion> soulQuestions = this.soulQuestionMapper.selectList(queryWrapper3);
            List<SoulQuestionVo> soulQuestionVos = new ArrayList<>();
            //填充SoulQuestionVo的数据
            for (SoulQuestion soulQuestion : soulQuestions) {
                SoulQuestionVo soulQuestionVo = new SoulQuestionVo();
                soulQuestionVo.setId(String.valueOf(soulQuestion.getId()));
                soulQuestionVo.setQuestion(soulQuestion.getStem());
                soulQuestionVos.add(soulQuestionVo);
                //SoulQuestionVo中还有一个List<SoulQuestionOptionVo> options-----选项集合没有填充
                QueryWrapper<SoulQuestionOption> queryWrapper4 = new QueryWrapper<>();
                queryWrapper4.in("question_id", soulQuestion.getId());
                List<SoulQuestionOption> soulQuestionList = this.soulQuestionOptionMapper.selectList(queryWrapper4);
                List<OptionVo> optionVos = new ArrayList<>();
                //填充soulQuestionOptionVo1数据
                for (SoulQuestionOption option : soulQuestionList) {
                    SoulQuestionOptionVo soulQuestionOptionVo = new SoulQuestionOptionVo();
                    soulQuestionOptionVo.setId(String.valueOf(option.getId()));
                    soulQuestionOptionVo.setContent(option.getContent());
                    //将soulQuestionOptionVo的值赋给OptionVo
                    OptionVo optionVo = new OptionVo();
                    optionVo.setId(soulQuestionOptionVo.getId());
                    optionVo.setOption(soulQuestionOptionVo.getContent());
                    optionVos.add(optionVo);
                }
                //把选项vo集合填充到问题对象中
                soulQuestionVo.setOptions(optionVos);

            }
            //把问题对象填充到返回问卷vo对象
            List<String> stringList = soulQuestionVos.stream().map(SoulQuestionVo::getId).collect(Collectors.toList());
            questionnaireVo.setQuestions(soulQuestionVos);
        }
        //System.out.println(questionnaireVoList);
        return questionnaireVoList;
    }

    /**
     * 测灵魂题目提交
     *
     * @param answersList
     */
    public String testSoul(List<Answers> answersList) {
        Integer score = 0;
        Long questionId = 0L;

        //计算分数
        for (Answers answers : answersList) {
            questionId = answers.getQuestionId();
            Long optionId = answers.getOptionId();

            LambdaQueryWrapper<SoulQuestionOption> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SoulQuestionOption::getId, optionId);
            SoulQuestionOption soulQuestionOption = soulQuestionOptionMapper.selectOne(queryWrapper);
            score += Integer.parseInt(soulQuestionOption.getScore());
        }

        //System.out.println(score);

        //通过题目id查到对应的问卷id
        SoulQuestion soulQuestion = soulQuestionMapper.selectById(questionId);
        Long questionnaireId = soulQuestion.getQuestionnaireId();   //问卷id

        //默认初级开启
        LambdaQueryWrapper<QuestionUserLock> queryWrapper = new LambdaQueryWrapper();
        if (questionnaireId<=2){
            queryWrapper.eq(QuestionUserLock::getQuestionnaireId, questionnaireId + 1)
                    .eq(QuestionUserLock::getUserId,UserThreadLocal.get().getId());
            QuestionUserLock questionUserLock = questionUserLockMapper.selectOne(queryWrapper);
            if(questionUserLock.getIsLock().equals(1)){
                questionUserLock.setIsLock(0);
                questionUserLockMapper.update(questionUserLock,queryWrapper);
            }
        }
        //根据问卷id,查看结果表，看总分在哪个区间，判断你的性格，并把数据都添加到报告表里
        LambdaQueryWrapper<QuestionnaireResult> query3 = new LambdaQueryWrapper<>();
        query3.eq(QuestionnaireResult::getQuestionnaireId, questionnaireId);
        List<QuestionnaireResult> questionnaireResults = questionnaireResultMapper.selectList(query3);

        QuestionnaireReport questionnaireReport = new QuestionnaireReport();
        questionnaireReport.setUserId(UserThreadLocal.get().getId());
        questionnaireReport.setQuestionnaireId(questionnaireId);    //问卷id
        for (QuestionnaireResult questionnaireResult : questionnaireResults) {
            String[] split = questionnaireResult.getScope().split(",");
            if (score >= Integer.valueOf(split[0]) && score <= Integer.valueOf(split[1])) {
                questionnaireReport.setResultId(questionnaireResult.getId());
                break;
            }
        }
        questionnaireReportMapper.insert(questionnaireReport);


        LambdaQueryWrapper<QuestionnaireReport> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QuestionnaireReport::getUserId,UserThreadLocal.get().getId())
                .eq(QuestionnaireReport::getQuestionnaireId,questionnaireId);
        QuestionnaireReport questionnaireReport1 = questionnaireReportMapper.selectOne(wrapper);

        return  questionnaireReport1.getId().toString();
    }

    /**
     * 灵魂测试结果
     * @param id
     * @return
     */
    public TestResultVo testResult(Long id) {
        TestResultVo testResultVo = new TestResultVo();
        List<Dimensions> dimensionList = new ArrayList<>();
        //通过id获取报告里面的数据
        QuestionnaireReport questionnaireReport = questionnaireReportMapper.selectById(id);
        Long resultId = questionnaireReport.getResultId();
        //通过报告表里面的resultId查询数据，写维度集合里
        QuestionnaireResult questionnaireResult = questionnaireResultMapper.selectById(resultId);
        dimensionList.add(new Dimensions("外向性","68%"));
        dimensionList.add(new Dimensions("判断力","79%"));
        dimensionList.add(new Dimensions("抽象性","52%"));
        dimensionList.add(new Dimensions("理性","90%"));

        //保存到testResultVo里面
        testResultVo.setConclusion(questionnaireResult.getContent());
        testResultVo.setCover(questionnaireResult.getCover());
        testResultVo.setDimensions(dimensionList);

        //通过resultId查询报告表，获取所有的用户，存到集合里
        QueryWrapper<QuestionnaireReport> queryWrapper = new QueryWrapper();
        queryWrapper.eq("result_id",resultId);
        List<QuestionnaireReport> questionnaireReports = questionnaireReportMapper.selectList(queryWrapper);
        List<Long> userIds = new ArrayList<>();
        for (QuestionnaireReport report : questionnaireReports) {
            userIds.add(report.getUserId());
        }

        //查询所有用户的完整信息
        QueryWrapper<UserInfo> queryWrapper1 = new QueryWrapper();
        queryWrapper1.in("user_id",userIds);
        List<UserInfo> userInfos = userInfoMapper.selectList(queryWrapper1);

        ArrayList<SimilarYou> similarYouList = new ArrayList<>();
        //如果是当前用户就跳过，否则添加到相似的人集合里
        for (UserInfo userInfo : userInfos) {
            if(UserThreadLocal.get().getId().equals(userInfo.getUserId())){
                continue;
            }
            similarYouList.add(new SimilarYou(Convert.toInt(userInfo.getUserId()),userInfo.getLogo()));
            //System.out.println(similarYouList);
        }

        testResultVo.setSimilarYou(similarYouList);
        return testResultVo;
    }
}
